<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>回到顶部</title>
    <style>
      /* 清空默认样式 */
        * {
          padding: 0;
          margin:0;
        }
        body {
          height: 3000px;
        }
       .container {
         width: 100%;
         height: 80px;
         line-height: 80px;
         position: fixed;
         color: white;
         top: -80px;
         font-size: 30px;
         text-align: center;
         background-color: skyblue;
       }
       .goTop {
         width: 50px;
         height: 60px;
         position: fixed;
         right: 20px;
         bottom: 20px;
         font-size: 20px;
         display: none;
       }
    </style>
</head>
<body>
  <div class="container">顶部通栏</div>
  <button class="goTop">回到顶部</button>
  <script>
      var container = document.querySelector('.container');
      var goTop =  document.querySelector('.goTop');
      window.onscroll = function () {
        //在滚动条位置发生的事件中实时获取滚动高度
        var height = document.documentElement.scrollTop;
        //判断高度
        if (height >= 300) {
          container.style.top = 0;
          goTop.style.display = 'block';
        }
        else {//不合格就不发生
            container.style.top = '-80px';
            goTop.style.display = 'none';
        }
      };
      //给按钮上个点击事件
      goTop.onclick = function () {
        window.scrollTo({
          top:0,
          behavior:"smooth",
        })
      }
  </script>
</body>
</html>